<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { getApi, updateApi } from '/@/api/mes/craft'
import { useInModal } from '/@/hooks/useModal'
import { useSuccessMessage } from '/@/hooks/useMessage'
import { dataFormatter } from '/@/utils/data'

const props = defineProps(({
  id: String
}))

const emits = defineEmits(['change'])

const modal = useInModal()

const formRef = ref<FormMakerInstance>();
const formProps = reactive<FormMakerProps>({
  name: 'craftForm',
  disabled: true,
  options: [
    { field: "code", label: "工单编号" },
    {
      field: "productId", label: "产品", required: true, component: {
        key: 'SelectMaker',
        props: {
          dataSource: 'Product'
        }
      }
    },
    { field: "planStartDate", label: "计划开始", component: 'ElDatePicker' },
    { field: "quantity", label: "数量" }
  ]
})

const tableRef = ref<YTableInstance>()
const tableProps = reactive<YTableProps>({
  height: 'auto',
  data: [],
  columns: [
    {
      field: "processId", label: "工序", width: 100,
      edit: true,
      editComponent: {
        key: 'SelectMaker',
        props: {
          dataSource: 'Process'
        }
      },
      formatter: (v) => dataFormatter(v, 'Process')
    },
    { field: "planWorkingTime", label: "计划工时", width: 100, edit: true },
    { field: "planStartTime", label: "计划开始", width: 135, edit: true, editComponent: 'ElDatePicker', formatter: 'date' },
    { field: "planEndTime", label: "计划结束", width: 135, edit: true, editComponent: 'ElDatePicker', formatter: 'date' },
    { field: "remark", label: "备注", edit: true },
  ],
  editOperas: ['add', 'delete', 'fill', 'copy', 'drag'],
  config: {
    edit: true
  }
})

const loadViewData = () => {
  if (props.id) {
    modal.loading(true)
    getApi(props.id)
      .then((res: any) => {
        formRef.value.setData(res.data)
        tableProps.data = res.data.crafts
      })
      .finally(() => modal.loading(false))
  }
}

watch(() => props.id, (id: string) => {
  loadViewData()
}, { immediate: true })

const handConfirm = async (btnName: string) => {

  await formRef.value.validate()

  modal.loadingWarp(async () => {
    const postData = {
      workOrderId: props.id,
      crafts: tableRef.value.getData()
    }
    await updateApi(postData)

    useSuccessMessage(btnName + '成功');
    emits('change')
    loadViewData()
  })
}


const viewLayout: ViewLayoutProps = {
  buttons: [
    {
      title: '保存',
      type: 'primary',
      onClick: handConfirm
    },
    { title: '取消', onClick: () => modal.close() },
  ]
}



</script>

<template>
  <ViewLayout v-bind="viewLayout">
    <template #header>
      <FormMaker v-bind="formProps" ref="formRef" />
    </template>
    <YTable v-bind="tableProps" ref="tableRef"></YTable>
  </ViewLayout>
</template>